package com.zhiliao.common.captcha;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * Description: 验证码控制器
 *
 * @author qirong
 * @create 2018-10-26
 */
@Controller
public class CaptchaController {

    private final static Logger log = LoggerFactory.getLogger(CaptchaController.class);

    @Autowired
    private Producer captchaProducer;


    @RequestMapping("/verify")
    public ModelAndView doGet(HttpServletResponse response, HttpSession session) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        /* 生成验证码文本 */
        String capText = captchaProducer.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY,capText);
        log.debug("captchaProducer.createText："+capText);

        /* 利用生成的字符串构建图片 */
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out  = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }

    @RequestMapping("/verify/validate")
    @ResponseBody
    public String validateVerifyCode(@RequestParam("verifyCode") String verify,HttpSession session) {

        boolean boo = false;
        JSONObject result = new JSONObject();
        Object obj = session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if(null != obj) {
            if(obj instanceof String) {
                String text = (String) obj;
                if(StringUtils.isNotBlank(text) && StringUtils.isNotBlank(verify) && verify.equals(text)) {
                    boo = true;
                }
            }
        }
        if(boo) {
            result.put("ok","验证码输入正确！");
        } else {
            result.put("error","验证码错误,请刷新或重新输入！");
        }
        return result.toJSONString();
    }

}
